"use client";
import React, { useEffect } from "react";
import { useFormState } from "react-dom";
import { register } from "@/lib/action";
import { useRouter } from "next/navigation";

const RegisterForm = () => {
  // must used in client
  const [state, formAction] = useFormState(register, {});
  const router = useRouter();
  useEffect(() => {
    if (state.code === 0) {
      router.replace("/login");
    }
  }, [state, router]);

  return (
    <form action={formAction}>
      <input type="text" name="username" placeholder="Username" />
      <input type="email" name="email" placeholder="email" />
      <input type="password" name="password" placeholder="password" />
      <input
        type="password"
        name="passwordRepeat"
        placeholder="password again"
      />
      <button>register</button>
      {state?.reason && <p>{state.reason}</p>}
    </form>
  );
};

export default RegisterForm;
